<?php 
namespace Hdphp\Controller;

class Controller
{
    //事件参数
    protected $options = array();

    public function __construct()
    {
        
     Hook::listen('controller_start', $this->options);

        if(method_exists($this, '__init'))
        {
            $this->__init();
        }
    }

    /**
     * 分配变量
     * @param  [type] $name  [description]
     * @param  [type] $value [description]
     * @return [type]        [description]
     */
    protected function assign($name,$value)
    {
        View::with($name,$value);
    }

    /**
     * 显示模板
     * @param  [type] $tpl [description]
     * @return [type]      [description]
     */
    protected function display($tpl='')
    {
        View::make($tpl);
    }

    /**
     * 通过魔术方法设置变量
     * @param [type] $name  [description]
     * @param [type] $value [description]
     */
    public function __set($name,$value)
    {
        $this->assign($name,$value);
    }

    public function validate($validates)
    {
        $validator = Validate::make($validates);
        if($validator->fail())
        {
            //验证失败
            if(IS_AJAX)
            {
                $response=array(
                    'state'=>402,
                    'message'=>$validator->message()
                );

                $this->ajax($response);
            }
            else
            {
                View::error($validator->message());
            }
        }
    }

    protected function success($message = '操作成功', $url = null, $time = 1, $tpl = null)
    {
        if (IS_AJAX)
        {
            $this->ajax(array('status' => 1, 'message' => $message));
        }
        else
        {
            View::success($message, $url, $time, $tpl);
        }
    }

    protected function error($message = '操作失败', $url = null, $time = 1, $tpl = null)
    {
        if (IS_AJAX) 
        {
            $this->ajax(array('status' => 0, 'message' => $message));
        }
        else
        {
            View::error($message, $url, $time, $tpl);
        }
    }

    /**
     * Ajax输出
     * @param $data 数据
     * @param string $type 数据类型 text html xml json
     */
    protected function ajax($data, $type = "JSON")
    {
        $type = strtoupper($type);
        switch ($type) {
            case "HTML" :
            case "TEXT" :
                $_data = $data;
                break;
            case "XML" :
                //XML处理
                header( 'Content-Type: application/xml' );
                $_data = Xml::create($data);
                break;
            default :
                //JSON处理
                header( 'Content-Type: application/json' );
                $_data = json_encode($data);
        }
        echo $_data;
        exit;
    }

    public function __destruct()
    {
        Hook::listen('controller_end', $this->options);
    }
}